package com.senney.practice.nio.test;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;

public class BufferDemo {
    @Test
    public void testMark() {
        String str = "abcde";
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        buffer.flip();
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes, 0, 2);
        System.out.println(new String(bytes, 0, 2));
        System.out.println(buffer.position());

        buffer.mark();
        buffer.get(bytes, 2, 2);
        System.out.println(new String(bytes, 0, 2));
        System.out.println(buffer.position());

        buffer.reset();
        System.out.println(buffer.position());

        if(buffer.hasRemaining()){
            System.out.println(buffer.remaining());
        }
    }

    @Test
    public void testBuffer() {
        String str = "abcde";

        // 分配一个指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("================allocate==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());

        // 利用put方法存储数据
        buffer.put(str.getBytes());
        System.out.println("================put==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());

        // 切换读取数据模式
        buffer.flip();
        System.out.println("================flip==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());

        // 利用get方法读取数据
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes);
        System.out.println(new String(bytes, 0, bytes.length));
        System.out.println("================get==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());

        // 可重复读数据
        buffer.rewind();
        System.out.println("================rewind==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());

        // clear清空缓冲区，但缓冲区的数据依然存在，处于“被遗忘”状态
        buffer.clear();
        System.out.println("================clear==================");
        System.out.println("capacity: " + buffer.capacity());
        System.out.println("limit: " + buffer.limit());
        System.out.println("position: " + buffer.position());
    }
}
